package com.running.base.run.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.activation.DataHandler;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.security.Security;
import java.util.Map;
import java.util.Properties;

@Component
public class SendMailDBFile {

    private static final Logger logger = LoggerFactory.getLogger(SendMailDBFile.class);

    @Value("${sender.email}")
    private String EMAIL_USERNAME;

    @Value("${sender.email.paswd}")
    private String EMAIL_PASSWORD;

    @Value("${sender.email.smtp}")
    private String SMTP_HOST;

    @Value("${server.manager}")
    private String receive_email;

    @Value("${sender.email.port}")
    private String myEmailSMTPPort;

    @Value("${email.application.name}")
    private String mailAppName;

    public SendMailDBFile() {
        logger.info("邮箱功能客户端2启动完成！");
    }


    public void sendEmailWithAttachment(Map<String, String> fileNameMap, String content) throws Exception {
        try {
            // 使用port=25端口的配置情况
//            Properties props = new Properties();
//            props.put("mail.smtp.auth", "true");
//            props.put("mail.smtp.starttls.enable", "true");
//            props.put("mail.smtp.host", SMTP_HOST);
//            props.put("mail.smtp.connectiontimeout", "6000")

            Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", SMTP_HOST);
            props.put("mail.smtp.connectiontimeout", "6000");
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.smtp.port", myEmailSMTPPort);
            props.setProperty("mail.smtp.socketFactory.port", myEmailSMTPPort);

            if (EMAIL_USERNAME.contains("outlook")) {//outlook邮箱
                props.setProperty("mail.smtp.ssl.protocols", "TLSv1.2");
            } else {
                final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
                props.setProperty("mail.smtp.socketFactory.class", SSL_FACTORY);
            }

            Session session = Session.getInstance(props, new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(EMAIL_USERNAME, EMAIL_PASSWORD);
                }
            });
            session.setDebug(true);

            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress(EMAIL_USERNAME, mailAppName, "UTF-8"));
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(receive_email));
            message.setSubject("DB每日备份任务结果");

            MimeMultipart multipart = new MimeMultipart();

            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setContent(content + "<br>DB每日备份任务结果已上传，请下载附件查看。", "text/html;charset=UTF-8");
            multipart.addBodyPart(messageBodyPart);

            // 添加附件
            if (!CollectionUtils.isEmpty(fileNameMap)) {
                for (String filePath : fileNameMap.keySet()) {
                    MimeBodyPart attachment  = new MimeBodyPart();
                    attachment.setDataHandler(new DataHandler(new FileDataSource(filePath)));
                    attachment.setHeader("Content-Disposition", "attachment; filename=" + fileNameMap.get(filePath));
                    multipart.addBodyPart(attachment);
                }
            }

            // 将多部分内容设置为邮件的内容
            message.setContent(multipart);
            Transport.send(message);
            logger.info("邮件已发送。接收者=" + receive_email);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("邮件发送出现异常：" + e.getMessage());
            throw e;
        }
    }
}
